package com.wn.sk.product.core.controller;


import com.wn.common.api.Result;
import com.wn.common.api.order.dto.OrderPayDto;
import com.wn.common.api.status.impl.ResultCode;
import com.wn.sk.product.core.exception.BusinessException;
import com.wn.sk.product.core.service.IPromotionSeckillService;
import com.wn.sk.product.core.vo.PaymentVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 秒杀活动表 前端控制器
 * </p>
 *
 * @author yellow docker
 * @since 2022-09-02
 */
@RestController
@RequestMapping("/promotion-seckill")
@Api(tags = "秒杀活动")
@Slf4j
public class PromotionSeckillController {

    @Autowired
    private IPromotionSeckillService promotionSeckillService;

    //秒杀活动测试
    @ApiOperation(value = "秒杀活动测试")
    @ApiImplicitParam(defaultValue = "1")
    @GetMapping("/auth/test/{promotionId}")
    public Result<String> test(@PathVariable("promotionId") Integer promotionId, HttpServletRequest request){

        String userId = request.getHeader("userId");

        log.info("当前的用户id是:{}",userId);

        log.info("过来秒杀抢东西了....");
        return Result.ok();
    }

    //秒杀活动
    @ApiOperation(value = "秒杀活动生成订单")
    @ApiImplicitParam(defaultValue = "1")
    @GetMapping("/auth/order/{promotionId}")
    public Result submitOrder(@PathVariable("promotionId") Integer promotionId, HttpServletRequest request){
        String userId = request.getHeader("userId");
        log.info("当前的用户id是:{}",userId);

        //秒杀订单的返回结果
        Result result =promotionSeckillService.submitOrder(promotionId,userId);
        return result;
    }

    /**
     * 确认订单
     * @param orderPayDto
     * @return
     *  请求路径添加 auth 为了鉴权 ( 需要认证才可以访问 )
     */
    @PostMapping("/auth/order/confirm")
    @ApiOperation("确认订单")
    public Result confirmOrder(@RequestBody OrderPayDto orderPayDto, HttpServletRequest request){

        //获取头信息中的 userId
        String userId = request.getHeader("userId");

        //将订单待支付的信息，存储到MQ中。
        try {
            PaymentVo vo = promotionSeckillService.confirmOrder(orderPayDto,userId);
            //返回待支付的订单数据。
            return Result.common(vo);
        } catch (Exception e) {
            return Result.error(500001,"确认订单失败");
        }
    }

    @PutMapping("/auth/pay")
    @ApiOperation("订单支付")
    public Result pay(@RequestBody OrderPayDto orderPayDto){
        try {
            Integer status = promotionSeckillService.payOrder(orderPayDto);
            return Result.common(status);
        } catch (BusinessException e) {
            return Result.error(200000,"付款失败....");
        }
    }

}

